package com.malty.gateway.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malty.common.ErrorCode;
import com.malty.common.domain.Result;
import com.malty.common.util.ResultUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常通用处理器
 */
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {


    private final ObjectMapper objectMapper;


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        // 打印异常日志
        printExceptionLog(request, ex);
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
        }
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                if (hasInvalidSignatureMsg(ex)) {
                    Result<Void> result = ResultUtils.error(ErrorCode.SIGNATURE_ERROR, ex.getMessage());
                    return bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
                }
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(ResultUtils.error(ErrorCode.SIGNATURE_ERROR, ex.getMessage())));
            } catch (JsonProcessingException e) {
                log.error("Error writing response", ex);
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }

    private void printExceptionLog(ServerHttpRequest request, Throwable ex) {
        String logStr = "#handle ServerWebExchange, id:{}, URI:{}, path:{}, method:{}, " +
                "remoteAddress:{}," +
                "queryParams:{}, headers:{}, " +
                "cookies:{}, threadName:{} " +
                "Exception:";
        
        Object[] logVal = {request.getId(), request.getURI(), request.getPath(), request.getMethod(),
                request.getRemoteAddress(),
                request.getQueryParams(), request.getHeaders(),
                request.getCookies(), Thread.currentThread().getName(),
                ex};

        log.error(logStr, logVal);
    }

    private boolean hasInvalidSignatureMsg(Throwable ex) {
        if (null != ex && null != ex.getMessage() && ex.getMessage().equals(ErrorCode.SIGNATURE_ERROR.getMessage())) {
            return true;
        }
        return false;
    }
}
